/**
 * Created by elvis on 2018/9/26
 * 公共会员卡Mixin
 */
import wepy from 'wepy'
import constant from '../utils/constant.utils.js'
import { bizShareDataReport } from '../utils/share.utils.js'
import { vipCardActive } from '../api/index.js'
import {
  memberWelfare,
  memberRegisterInfo,
  checkWeChatCardState,
  getUserCardInfo
} from '../api/index.js'

// 是否已注册过微信会员卡标记
let isRegisterWeChatCard = false

export default class MemberMixin extends wepy.mixin {
  data = {
    isWeChatCard: false, // 是否开通微信会员卡
    weChatCardInfo: '', // 微信会员卡card_id和code
    memberWelfare: {}, // 会员权益信息
    memberCartExtraData: {}, // 会员卡组件参数
    navigateMiniProgramByApi: true // 是否通过api跳转小程序
  }

  /**
   * 跳转到微信会员卡注册
   * @param {String} appId 固定为wxeb490c6f9b154ef9
   * @param {Object} extraData 开卡组件参数，包含以下三个参数
   * @param {String} encrypt_card_id 加密 card_id，后端返回已经urldecode
   * @param {String} outer_str 会员卡领取渠道值，会在卡券领取事件回传给商户
   * @param {String} biz 商户公众号标识参数，后端返回已经urldecode
   * @see https://developers.weixin.qq.com/miniprogram/dev/api/card.html#%E4%BC%9A%E5%91%98%E5%8D%A1%E7%BB%84%E4%BB%B6
   */
  navigateToMiniProgram() {
    if (
      this.isWeChatCard &&
      this.memberCartExtraData &&
      this.memberCartExtraData.encrypt_card_id
    ) {
      wx.navigateToMiniProgram &&
        wx.navigateToMiniProgram({
          appId: constant.cardAppId,
          extraData: this.memberCartExtraData
        })
    }
  }

  /**
   * 获取会员卡注册组件信息
   */
  getMemberRegisterInfo() {
    return new Promise((resolve, reject) => {
      wx.$request(memberRegisterInfo, {
        data: {
          outerStr: constant.bizType
        }
      }).then(({ data }) => {
        if (data.url) {
          resolve(this.parseUrlParams(data.url))
        } else {
          resolve({})
        }
      })
    })
  }

  /**
   * 获取会员等级权益
   *
   * @return {Number} userLevel 会员等级（0表示不是会员）
   * @return {Boolean} isOnVipCard 商家是否开通会员卡
   * @return {String} cardName 会员对应等级（不是会员则为则为最低等级会员）的会员卡名称
   * @return {Array} welfareNameList 企业所有等级的权益信息
   * @return {Boolean} isGuideRegistration 会员对应等级（不是会员则为则为最低等级会员）是否享有优惠（除自定义）
   * @return {Number} levelDiscount 会员对应等级（不是会员则为则为最低等级会员）会员折扣包含的折扣值
   */
  queryMemberWelfare() {
    return new Promise((resolve, reject) => {
      wx.$request(memberWelfare)
        .then(({ data }) => {
          console.info('queryMemberWelfare:', data)
          if (
            data &&
            data.isOnVipCard &&
            data.welfareNameList &&
            JSON.stringify(data.welfareNameList) !== '{}'
          ) {
            // 用户显示的等级 如果不是会员则为最低等级
            const userLevel = data.userLevel || 1
            // 会员所属的等级权益, 并且过滤自定义权益
            if (data.welfareNameList[String(userLevel)]) {
              const levelWelfare = (data.welfareNameList[
                String(userLevel)
              ] = data.welfareNameList[String(userLevel)].filter(
                item => item.welfareType < 6
              ))
              // 最低等级是否有福利
              data.isGuideRegistration = !!(levelWelfare && levelWelfare.length)
              // 对应等级权益是否包含会员折扣
              const isDiscount = levelWelfare.some(
                item => Number(item.welfareType) === 1
              )
              if (isDiscount) {
                // 会员折扣包含的折扣值，如果不是会员则为最低的会员等级折扣值（订单确认的展示）
                data.levelDiscount = levelWelfare.filter(
                  item => Number(item.welfareType) === 1
                )[0].discount
              }
              this.memberWelfare = data
              this.$apply()

              // 获取微信会员卡开卡信息
              this.getMemberRegisterInfo().then(data => {
                this.memberCartExtraData = data
                // 判断跳转微信会员卡接口是否废弃
                this.navigateMiniProgramByApi = !!wx.navigateToMiniProgram
                this.$apply()
              })
            }
          }
          resolve(data)
        })
        .catch(({ data }) => {
          reject(data)
        })
    })
  }

  /**
   * 微信会员开卡激活
   */
  async memberCardActive() {
    // 修复会员开卡注册后延迟返回referrerInfo
    await this.sleep(300)
    let { extraData = {} } = wx.$getGlobalData().referrerInfo
    let params = this.parseUrlParams(extraData.wx_activate_after_submit_url)
    console.info(
      'wx_activate_after_submit_url:',
      params,
      this.memberWelfare,
      isRegisterWeChatCard
    )

    // 企业已开通会员卡、未注册会员、已配置最低会员权益、已经执行过注册会员卡操作
    if (
      !isRegisterWeChatCard &&
      params.openid &&
      params.encrypt_code &&
      extraData.card_id &&
      extraData.activate_ticket
    ) {
      wx.$tips.showLoading('会员开卡中')

      return new Promise((resolve, reject) => {
        wx.$request(vipCardActive, {
          data: {
            outerStr: constant.bizType,
            platformId: wx.$getGlobalData().openId,
            openid: params.openid,
            encryptCode: params.encrypt_code,
            cardId: extraData.card_id,
            activateTicket: extraData.activate_ticket
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          }
        })
          .then(({ data }) => {
            console.info('memberCardActive info:', data)
            if (data) {
              resolve(true)
              bizShareDataReport({
                performanceType: 2,
                performanceId: ''
              })
              this.routeGoRegisterResult()
              wx.$tips.toast('开卡成功')
              // wx.$navigateTo({ url: '/pages/register-result?state=success' })
            } else {
              reject(false)
              this.routeGoRegisterResult()
              wx.$navigateTo({ url: '/pages/register-result?state=failure' })
            }
          })
          .catch(({ data }) => {
            console.info('memberCardActive error:', data)
            reject(false)
            this.routeGoRegisterResult()
            wx.$navigateTo({ url: '/pages/register-result?state=failure' })
          })
      })
    } else {
      return Promise.resolve()
    }
  }

  /**
   * 微信开卡激活判断
   */
  routeGoRegisterResult() {
    isRegisterWeChatCard = true
    wx.$tips.hideLoading()
  }

  /**
   * 是否开通微信会员卡
   */
  checkWeChatCard() {
    return new Promise((resolve, reject) => {
      wx.$request(checkWeChatCardState, {
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        }
      })
        .then(({ data }) => {
          console.info('checkWeChatCard:', data)
          this.isWeChatCard = data
          this.$apply()
          resolve(data)
        })
        .catch(({ data }) => {
          reject(data)
        })
    })
  }

  /**
   * 获取微信会员卡card_id和code
   */
  getWeChatCardInfo() {
    return new Promise((resolve, reject) => {
      wx.$request(getUserCardInfo, {
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        }
      })
        .then(({ data }) => {
          console.info('getWeChatCardInfo:', data)
          this.weChatCardInfo = data || {}
          this.$apply()
          resolve(data)
        })
        .catch(({ data }) => {
          reject(data)
        })
    })
  }

  // 解析相关url请求query参数
  // https://mp.weixin.qq.com/bizmall/activatemembercard?action=preshow&&encrypt_card_id=BJXtk99o08e5/WHp1bq2KYXn9rVNj/fQ91WP/Qj67lWTwfEAjwOhRr18HmA7YAvB&outer_str=THEMATIC&biz=MzA3MzQ2MzA3NA==#wechat_redirect
  parseUrlParams(url) {
    let params = {}
    if (!url) return params
    let urlPath = url.split('#')[0].split('?')[1]
    urlPath.split('&').forEach(item => {
      let param = item.split('=')
      param[0] && (params[param[0]] = decodeURIComponent(param[1]))
    })
    console.info('parseUrlParams:', params)
    return params
  }

  // 获取会员等级权益
  getMemberConfig() {
    return new Promise((resolve, reject) => {
      wx.$request(memberWelfare).then(
        ({ data }) => {
          this.memberWelfare = data
          this.$apply()
          resolve(data)
        },
        data => {
          reject(data)
        }
      )
    })
  }

  // 处理引导会员注册
  async handleMemberRegister() {
    await this.getMemberConfig()
    if (!this.memberWelfare.isOnVipCard) return
    if (this.memberWelfare.userLevel === 0) {
      // 非会员引导注册：微信会员卡|云来会员卡
      if (this.isWeChatCard) {
        wx.$tips.showLoading()
        this.getMemberRegisterInfo().then(data => {
          this.memberCartExtraData = data
          this.$apply()
          wx.$tips.hideLoading()
          this.navigateToMiniProgram()
        })
      } else {
        wx.$navigateTo({ url: '/pages/register?source=delta' })
      }
    } else {
      wx.showModal({
        content: '您已经是会员了，去逛逛吧',
        showCancel: false,
        confirmText: '知道了'
      })
    }
  }
}
